<?php

/*
 * staff controller
 */
class ContactController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;
	protected $class;
	
	public function init() {
		//$this->_user = $this->checkLogin ();
		//print_r($this->_user);exit;
		/* Initialize action controller here */
		$this->controller = $this->getRequest ()->getControllerName ();
		$this->action = $this->getRequest ()->getActionName ();
		$this->commonTemplates ();
		
		$this->_smarty->assign ( 'controller', $this->controller );
		$this->_smarty->assign ( 'action', $this->action );
		$this->_smarty->assign ( '_user', $this->_user );
		
		$this->_smarty->assign ( 'title', 'Contact  ' );

		//get database
		$this->getDb ( 'osmdb' );
		
	//verify rights
	//	if (isset ( $this->_user->agentcode ))
	//		$this->_redirect ( '/' );
	

	}
	
	public function indexAction() {
		try {
			$count = 40; //pre
			$curpage = ( int ) $this->_request->getParam ( 'page' );
			if (! $curpage)
				$curpage = 1;
			$offset = ($curpage - 1) * $count;
			
			//获取setting 列表
			$sql='select * from arafmi_field';
			$field = $this->_dbAdapter->fetchAssoc ( $sql );
			
			//$sql = 'select SQL_CALC_FOUND_ROWS a.*,b.branch_name 
			//from arafmi_users a 
			//left join  arafmi_branch b on a.branch_id=b.branch_id 
			//order by a.`isdisabled` asc,a.uid asc ' . " limit $offset,$count";
			$sql = 'select SQL_CALC_FOUND_ROWS * from arafmi_contact order by Contact_Date Desc'. " limit $offset,$count";;
			$result = $this->_dbAdapter->fetchAssoc ( $sql );
			//print_r($result);
			foreach ( $result as $key => $value ) {
				$result [$key] ['Contact_Date'] = $value ['Contact_Date'] ? date ( 'd-m-Y H:i', $value ['Contact_Date'] ) : '';
				$result [$key] ['Contact_Type'] = $field[$value['Contact_Type']]['field_name'];				
				$result [$key] ['Contact_Method'] = $field[$value['Contact_Method']]['field_name'];				
				$result [$key] ['Contact_Source'] = $field[$value['Contact_Source']]['field_name'];		
				$result [$key] ['Client_Gender'] = $value ['Client_Gender'] ? 'Female' : 'Male';
				//$result [$key] ['sexDisp'] = $value ['sex'] ? 'Female' : 'Male';
			}
			
			//page controller
			$param ['file'] = '/' . $this->controller . '/' . $this->action;
			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' );
			$param ['perpagenum'] = $count; // number that dislpays in each page
			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
			$param ['curpage'] = $curpage; // current page number
			$this->_smarty->assign ( 'allnum', $param ['totalnum'] );
			
			//	require_once 'MyClass/class.page.php';
			$page = new MyClass_Page ( $param );
			//$page->setvar ( array ('gid' => $gradeid,'typeid'=>$typeid) );
			

			$this->_smarty->assign ( 'page', $page->getNumPage () );
			$this->_smarty->assign ( 'result', $result );
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//add contact action
	public function addAction() {
		try {
			//get field info
			$sql = "select field_type, field_ID, field_name from arafmi_field order by field_type asc, field_order asc";
			$field_tmp = $this->_dbAdapter->fetchAll ( $sql );
			$field=array();
			foreach($field_tmp as $key => $value){
				$field[$value['field_type']][$value['field_ID']]=$value['field_name'];
			}
			//print_r($field_tmp);
			unset($field_tmp );
			$this->_smarty->assign ( 'field', $field );		
		
			//print_r($fieldinfo);exit;
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
			//print_r($this->controller);
		//print_r($this->action);			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//operate add user action
	public function opaddAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( 'Parameter or argument errors!' );
			}
			$p = $this->_request->getPost ();
			//unset ( $p ['submitbutton'] );
			
			//day month year hour minute
			
			//$p ['Contact_Date'] = time ();
			$tmp_datetime = $p ['Date_Day'] ."-". $p ['Date_Month'] ."-". $p ['Date_Year'] ." ". $p ['Time_Hour'] .":". $p ['Time_Minute'] ." ". $p ['Time_Meridian'] ;

			unset($p ['Date_Day']);
			unset($p ['Date_Month']);
			unset($p ['Date_Year']);
			unset($p ['Time_Hour']);
			unset($p ['Time_Minute']);
			unset($p ['Time_Meridian']);			
			
			$p ['Contact_Date'] = strtotime($tmp_datetime);		
			$p ['Contact_Week'] = date("D",$p ['Contact_Date']);
			$p ['Contact_Hour'] = date("H",$p ['Contact_Date']);			
			
			//print_r($tmp_datetime);print_r($p ['Contact_Date']);exit;			
			//print_r(date("F j, Y, g:i a",$p ['Contact_Date']));exit;
			
			$Contact_Outcome=$p['Contact_Outcome']; //demengqi add
			unset($p['Contact_Outcome']); //demengqi add
			
			$Client_Interests=$p['Client_Interests']; //demengqi add
			unset($p['Client_Interests']); //demengqi add			

			$result = $this->_dbAdapter->insert ( 'arafmi_contact', $p );
			if ($result) {
				$insertid = $this->_dbAdapter->lastInsertId (); //demengqi add
				
				if (! empty($Contact_Outcome))
				{
					foreach($Contact_Outcome as $key => $value){   //demengqi add
						$this->_dbAdapter->insert ( 'arafmi_mutilselect', array('Contact_ID'=>$insertid,'field_ID'=>$value,'field_name'=>'Contact_Outcome','create_time'=>time())); //demengqi add
					} //demengqi add
				}
				if (! empty($Client_Interests))
				{
					foreach($Client_Interests as $key => $value){   //demengqi add
						$this->_dbAdapter->insert ( 'arafmi_mutilselect', array('Contact_ID'=>$insertid,'field_ID'=>$value,'field_name'=>'Client_Interests','create_time'=>time())); //demengqi add
					} //demengqi add
				}
				
				$this->feedback ( 'Saved successfully', 'Success', '/' . $this->controller, 'tip', 0 );
			} else {
				throw new Exception ( 'Saved failed!' );
			}
		
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//edit user action
	public function editAction() {
		try {
			
			$id = ( int ) $this->_request->getParam ( 'Contact_ID' );
			if (! $id)
				throw new Exception ( 'Parameter or argument errors!' );
			
			$sql = 'select * from arafmi_contact where Contact_ID=' . $id;
			$result = $this->_dbAdapter->fetchRow ( $sql );
			
			$this->_smarty->assign ( 'result', $result );
			//print_r($result);exit;
			//get field info
			$sql = "select field_type, field_ID, field_name from arafmi_field order by field_type asc, field_order asc";
			$field_tmp = $this->_dbAdapter->fetchAll ( $sql );
			$field=array();
			foreach($field_tmp as $key => $value){
				$field[$value['field_type']][$value['field_ID']]=$value['field_name'];
			}
			//print_r($field);exit;
			unset($field_tmp );
			$this->_smarty->assign ( 'field', $field );		
			//contact outcome selected
			$sql = 'select m.field_ID, m.field_name from arafmi_contact c left join arafmi_mutilselect m on c.Contact_ID=m.Contact_ID where c.Contact_ID=' . $id;
			$field_tmp = $this->_dbAdapter->fetchAll ( $sql );
			$field_select=array();
			foreach($field_tmp as $key => $value){
				$field_select[$value['field_name']][$value['field_ID']]=$value['field_ID'];
			}
			unset($field_tmp );		
			//print_r($field_select);exit;
			$this->_smarty->assign ( 'multiSelected', $field_select );
			
			//gender
			$this->_smarty->assign ( 'genderOptions', array (0 => 'Male', 1 => 'Female' ) );

			//yes or no
			$this->_smarty->assign ( 'yesnoOptions', array (0 => 'No', 1 => 'Yes' ) );
			
			//Branch
			$sqlArea = 'select branch_id, branch_name from arafmi_branch';
			$resultArea = $this->_dbAdapter->fetchPairs ( $sqlArea );
			$this->_smarty->assign ( 'resultArea', $resultArea );
			$this->_smarty->assign ( 'areaSelect', $result ['branch_id'] );
			
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//operate to edit user action
	public function opeditAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( 'Parameter or argument errors!' );
			}
			
			$p = $this->_request->getPost ();
			
			//print_r($p);
			// verify password
/* 			if (! empty ( $p ['password'] )) {
				if ($p ['password'] != $p ['repassword'])
					throw new Exception ( 'Passwords do not match. Please re-enter password.' );
					
				$p ['password'] = md5 ( $pass );
				unset ( $p ['repassword'] );
				
			} else {
				unset ( $p ['password'] );
				unset ( $p ['repassword'] );
			}
 */			
			//$p ['createtime'] = time ();
			//print_r( $p ); exit;
			$result = $this->_dbAdapter->update ( 'arafmi_contact', $p, 'Contact_ID=' . $p ['Contact_ID'] );
			
			if ($result) {
				$this->feedback ( 'Saved successfully', 'Success', '/' . $this->controller, 'tip', 0 );
			} else {
				throw new Exception ( 'Save failed' );
			}
		
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//delete user
	public function deleteAction() {
		try {
			$id = ( int ) $this->_request->getParam ( 'Contact_ID' );
			if (! $id)
				throw new Exception ( 'Parameter or argument errors!' );
			
			$del_result = $this->_dbAdapter->delete ( 'arafmi_contact', 'Contact_ID=' . $id );
			if ($del_result) {
				//print_r($this->controller);
				$del_result = $this->_dbAdapter->delete ( 'arafmi_mutilselect', 'Contact_ID=' . $id );
				$this->feedback ( 'Deleted successfuly, please refresh to check!', 'Success', '/' . $this->controller, 'tip', 0 );
			} else {
				throw new Exception ( 'Deleted failed or have already deleted, please refresh to check!' );
			}
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//reserve statement as below
	public function noRouteAction() {
		$this->_redirect ( '/' );
	}
	
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		
		throw new Exception ( 'Invalid method' );
		
		// all other methods throw an exception
		throw new Exception ( 'Invalid method "' . $method . '" called' );
	}
}

